package com.etoak.controller;

import com.etoak.commons.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
public class UploadController {

    //读取yml文件配置项
    @Value("${image.dir}")
    String uploadDir;

    @Value("${image.path}")
    String pathPrefix;

    public static final String JPG = "image/jpeg";

    public static final String PNG = "image/png";

    @PostMapping("/upload")
    public ResultVO upload(MultipartFile file){

        //判断文件是否为空
        if(ObjectUtils.isEmpty(file) || file.getSize() <= 0){
            return ResultVO.error("文件不能为空");
        }

        //2.判断文件类型
        String contentType = file.getContentType();
        if(!StringUtils.equalsAnyIgnoreCase(contentType,PNG,JPG)){
            return ResultVO.error("仅支持PNG或JPG图片格式!");
        }
        //3.修改文件名称
        String originalFilename = file.getOriginalFilename();

        //文件扩展名称
        String extension = FilenameUtils.getExtension(originalFilename);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFilename = StringUtils.join(uuid,".",extension);

        //4.创建目标文件夹
        File destDir = new File(this.uploadDir);
        if(!destDir.exists()){
            destDir.mkdirs();
        }

        //5.创建目标文件
        File destFile = new File(destDir,newFilename);

        //6.上传文件
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            return ResultVO.error("图片上传失败");
        }

        String path = pathPrefix.endsWith("/") ?
                StringUtils.join(pathPrefix,newFilename) :
                StringUtils.join(pathPrefix,"/",newFilename);
        return ResultVO.success(path);
    }
}
